<template>
  <div class="dataVisualize-box">
    <div class="card top-box">
      <div class="top-title">统计数据可视化</div>
      <div style="display: flex; align-items: center; justify-content: center; width: 40%; margin-left: 30%">
        <el-select v-model="unit_select" style="" @change="changeTab">
          <el-option v-for="item in tab" :key="item.name" :label="item.label" :value="item.name" />
        </el-select>
        <div class="block">
          <el-date-picker
            v-model="clock"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="changeTime"
          />
        </div>
      </div>
      <div class="top-content" style="padding-bottom: 20px">
        <el-row :gutter="40">
          <el-col class="mb40" :span="9">
            <div class="item-right">
              <div class="echarts-title">不合格数/ 异常数 / 漏检数 / 完成数 占比</div>
              <div class="book-echarts">
                <Pie ref="pieRef" :pie-data="pieData" />
              </div>
            </div>
          </el-col>
          <el-col class="mb40" :span="15">
            <div class="card bottom-box">
              <div class="curve-echarts">
                <Curve ref="curveRef" :curve-data="curveData" />
              </div>
            </div>
          </el-col>
        </el-row>
        <div class="card bottom-box" style="padding-bottom: 20px">
          <el-table ref="tableRef" :data="tableData" height="auto" border class="custom-table">
            <!--子表格-->
            <el-table-column type="expand">
              <template #default="props">
                <el-table
                  ref="tableRef"
                  :data="props.row.members"
                  height="auto"
                  :show-header="false"
                  border
                  class="custom-table child-table"
                >
                  <!-- <el-table-column></el-table-column> -->
                  <el-table-column prop="name" :label="label1"> </el-table-column>
                  <el-table-column prop="finishNum" label="完成数"> </el-table-column>
                  <el-table-column prop="abnormalNum" label="异常数"></el-table-column>
                  <el-table-column prop="timeoutNum" label="不合格数"></el-table-column>
                  <el-table-column prop="cheatNum" label="漏检数"></el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column prop="name" :label="label2"> </el-table-column>
            <el-table-column prop="finishNum" label="完成数"> </el-table-column>
            <el-table-column prop="abnormalNum" label="异常数"></el-table-column>
            <el-table-column prop="timeoutNum" label="不合格数"></el-table-column>
            <el-table-column prop="cheatNum" label="漏检数"></el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="js">
import { onMounted, ref, computed } from "vue";
import Pie from "./dataVisualize/components/pie.vue";
import Curve from "./dataVisualize/components/curve.vue";
import { getAllClassService } from "@/api/systemManage/class.js";
import { getUnitDataService, getAllUnitDataService } from "@/api/inspection/home.js"; //, getClassMemberDataService
import { getAllUnitService } from "@/api/systemManage/unit.js";

function formatDate(date) {
  const year = date.getFullYear(); // 获取年份
  const month = date.getMonth() + 1; // 获取月份，月份从0开始，所以需要加1
  const day = date.getDate(); // 获取日期

  const formattedMonth = String(month).padStart(2, "0");
  const formattedDay = String(day).padStart(2, "0");

  return `${year}-${formattedMonth}-${formattedDay}`;
}

const tab = ref([{ label: "所有班组", name: -1 }]);
const classOrMember = ref(true);
const classOrUnit = ref(false);

const tableData = ref([
  {
    name: "班组1",
    cheatNum: 3,
    abnormalNum: 9,
    timeoutNum: 10,
    inspectionNum: 70, //完成数
    members: [
      {
        cheatNum: 45,
        abnormalNum: 27,
        timeoutNum: 16,
        finishNum: 99,
        Id: "",
        name: ""
      }
    ]
  }
]);

const clock = ref([]);
const time = ref({
  startDate: "",
  endDate: ""
});

//当前默认数据时间段为当月一号到当日
const getDefaultTime = () => {
  // 获取今天的日期
  const today = new Date();
  // 获取本月第一天的日期
  const startDate = new Date(today.getFullYear(), today.getMonth(), 1);
  // 如果今天是1号，则startDate为上个月的最后一天
  if (today.getDate() === 1) {
    startDate.setMonth(today.getMonth() - 1);
    startDate.setDate(0); // 设置为上个月的最后一天
  }
  const endDate = formatDate(today);

  time.value.endDate = endDate;
  time.value.startDate = formatDate(startDate);
  clock.value = [time.value.startDate, time.value.endDate];
};

const changeTime = value => {
  time.value.startDate = value[0];
  time.value.endDate = value[1];
  getAllData();
};

//获取班组&机组
const unit_select = ref(-1);

const classes = ref([]);
const units = ref([]);

const getAllClass = async () => {
  classes.value = [];
  let result = await getAllClassService();
  classes.value = result.data.data;
};

const getAllUnit = async () => {
  units.value = [];
  tab.value = [{ label: "所有机组", name: -1 }];
  let result = await getAllUnitService();
  units.value = result.data.data;
  units.value.forEach(item => {
    tab.value.push({
      label: item.unitName,
      name: item.unitId
    });
  });
};

const changeTab = () => {
  console.log(unit_select.value);
  if (unit_select.value == -1) {
    classOrMember.value = true;
    classOrUnit.value = false;
  } else {
    classOrMember.value = false;
    classOrUnit.value = true;
  }
  getAllData();
};

//图表数据
const pieData = ref([
  { value: 375, name: "完成数" },
  { value: 51, name: "漏检次数" },
  { value: 35, name: "异常次数" },
  { value: 37, name: "不合格数" }
]);

const curveData = ref([
  { teamName: "班组1", missed: 3, exception: 9, unqualified: 10, finish: 70 },
  { teamName: "班组2", missed: 7, exception: 2, unqualified: 6, finish: 55 },
  { teamName: "班组3", missed: 5, exception: 6, unqualified: 5, finish: 80 },
  { teamName: "班组4", missed: 10, exception: 5, unqualified: 8, finish: 50 },
  { teamName: "班组5", missed: 20, exception: 8, unqualified: 5, finish: 30 },
  { teamName: "班组6", missed: 6, exception: 5, unqualified: 3, finish: 90 }
]);

//获取数据
const getAllData = async () => {
  tableData.value = [];
  if (unit_select.value == -1) {
    try {
      let result = await getAllUnitDataService(time.value);
      //饼图
      pieData.value[0].value = result.data.data.total.finishNum;
      pieData.value[1].value = result.data.data.total.cheatNum;
      pieData.value[2].value = result.data.data.total.abnormalNum;
      pieData.value[3].value = result.data.data.total.timeoutNum;
      //表格
      result.data.data.units.forEach(unit => {
        let classes = [];
        unit.classes.forEach(classItem => {
          const class_member = {
            cheatNum: classItem.cheatNum,
            abnormalNum: classItem.abnormalNum,
            timeoutNum: classItem.timeoutNum,
            finishNum: classItem.finishNum,
            Id: classItem.classId,
            name: classItem.className
          };
          classes.push(class_member);
        });
        const member = {
          name: unit.unitName,
          cheatNum: unit.cheatNum,
          abnormalNum: unit.abnormalNum,
          timeoutNum: unit.timeoutNum,
          finishNum: unit.finishNum,
          members: classes
        };
        tableData.value.push(member);
      });
      //柱图
      curveData.value = tableData.value.map(item => ({
        teamName: item.name,
        missed: item.cheatNum,
        exception: item.abnormalNum,
        unqualified: item.timeoutNum,
        finish: item.finishNum
      }));
    } catch (error) {
      console.log("fail1", error);
    }
  } else {
    console.log("单一机组");
    try {
      let result = await getUnitDataService(time.value, unit_select.value);
      //饼图
      pieData.value[0].value = result.data.data.total.finishNum;
      pieData.value[1].value = result.data.data.total.cheatNum;
      pieData.value[2].value = result.data.data.total.abnormalNum;
      pieData.value[3].value = result.data.data.total.timeoutNum;
      //表格
      result.data.data.classes.forEach(classItem => {
        let memberList = [];
        classItem.members.forEach(item => {
          const classMember = {
            cheatNum: item.cheatNum,
            abnormalNum: item.abnormalNum,
            timeoutNum: item.timeoutNum,
            finishNum: item.finishNum,
            Id: item.userId,
            name: item.username
          };
          memberList.push(classMember);
        });
        const member = {
          name: classItem.className,
          cheatNum: classItem.cheatNum,
          abnormalNum: classItem.abnormalNum,
          timeoutNum: classItem.timeoutNum,
          finishNum: classItem.finishNum,
          members: memberList
        };
        tableData.value.push(member);
      });
      //柱图
      curveData.value = tableData.value.map(item => ({
        teamName: item.name,
        missed: item.cheatNum,
        exception: item.abnormalNum,
        unqualified: item.timeoutNum,
        finish: item.inspectionNum
      }));
    } catch (error) {
      console.log("fail2", error);
    }
  }
};

const label1 = computed(() => {
  return classOrMember.value ? "班组名称" : "成员名称";
});

const label2 = computed(() => {
  return classOrUnit.value ? "班组名称" : "机组名称";
});

onMounted(async () => {
  //获取默认时间
  getDefaultTime();
  //获取所有班组
  await getAllClass();
  //获取所有机组
  await getAllUnit();
  //获取数据并且渲染
  await getAllData();
});
</script>

<style scoped lang="scss">
@import "./index";
</style>
